<?php

class PointMode extends Data{
    /** @return PointMode */
    public static function init() {
        return parent::init();
    }
    //积分历史明细
    function getList($user_id,$rows = 30,$offset = 0){
        $rows=(int)$rows;
        $offset=(int)$offset;
        $sql="SELECT SQL_CALC_FOUND_ROWS * FROM `point_history` WHERE `user_id`=?
              ORDER BY `date` DESC ,`id` DESC   LIMIT $offset,$rows";
        return $this->db->getList($sql,$user_id);
    }
    //获得用户积分
    function getPoint($user_id){
        $sql="SELECT `point` FROM `user_info` WHERE `user_id`=?";
        return (int)$this->db->getValue($sql,$user_id);
    }

    //返还积分,也许会用到，退货什么的
    function returnPoint($user_id,$value){
        $sql="UPDATE `user_info` SET `point`=`point`+? WHERE `user_id`=?";
        return $this->db->sqlExec($sql,$user_id)==1;
    }
    function addToHistory($user_id,$value,$remark,$growthChange){
        $sql="SELECT * FROM `user_info` WHERE `user_id`=?";
        $userInfo=$this->db->getOne($sql,$user_id);
        $data['user_id']=$user_id;
        $data['point']=$value;
        $data['total']=$userInfo['point'];
        $data['growth']=$userInfo['growth']+(int)$growthChange;
        $data['date']=date('Y-m-d',time());
        $data['remark']=$remark;
        return $this->db->insert('point_history',$data)==1 ? true:false;
    }
    function earnPoint($user_id,$value,$remark,$growthChange = 0){
        $sql="UPDATE `user_info` SET `point`=`point`+? WHERE `user_id`=?";
        if($this->db->sqlExec($sql,$value,$user_id)==1){
            return $this->addToHistory($user_id,+$value,$remark,$growthChange)?true:false;
        }
        return false;
    }
    //使用积分 并存入明细表
    function usePoint($user_id,$value,$remark,$growthChange = 0){
        $sql="UPDATE `user_info` SET `point`=`point`-? WHERE `user_id`=?";
        if($this->db->sqlExec($sql,$value,$user_id)==1){
            return $this->addToHistory($user_id,-$value,$remark,$growthChange)?true:false;
        }
        return false;
    }
    //使用积分的时候检查一下ok？
    function checkPointValid($user_id,$value){
        return $this->getPoint($user_id) >= (int)$value;
    }
} 